package pemks.servlet;/**
 * @description:  
 * @author kl
 * @date 2025/4/4 下午9:36
 * @version 1.0
 */
import java.io.*;
import java.sql.*;
import java.util.Enumeration;
import java.util.List;

import com.google.gson.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import pemks.dao.UserDAO;
import pemks.entity.User;


@WebServlet(
        name = "UserServlet",
        urlPatterns = {"/smartgrid/register", "/smartgrid/login",
                "/smartgrid/manager_login","/smartgrid/getuser_pk",
                "/smartgrid/get_alluser"},
        loadOnStartup = 1
)
public class UserServlet extends HttpServlet {
    private UserDAO userDAO = new UserDAO();

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        response.setContentType("application/json;charset=UTF-8");
        String path = request.getPathInfo();
        JsonObject jsonResponse = new JsonObject();

        try {
            switch(path) {
                case "/register":
                    handleRegistration(request, jsonResponse);
                    break;
                case "/login":
                    handleUserLogin(request, jsonResponse);
                    break;
                case "/manager_login":
                    handleAdminLogin(request, jsonResponse);
                    break;
                case "/getuser_pk":
                    handleGetPublicKey(request, jsonResponse);
                    break;
                default:
                    sendError(response, 404, "Not Found");
            }
        } catch (Exception e) {
            sendError(response, 500, "Server Error: " + e.getMessage());
        }

        response.getWriter().print(jsonResponse.toString());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        String path = request.getPathInfo();
        JsonObject jsonResponse = new JsonObject();

        try {
            switch(path) {
                case "/get_alluser":
                    handleGetAllUsers(request, jsonResponse);
                    break;
                default:
                    sendError(response, 404, "Not Found");
            }
        } catch (Exception e) {
            sendError(response, 500, "Server Error: " + e.getMessage());
        }

        response.getWriter().print(jsonResponse.toString());
    }

    // 用户注册处理
    private void handleRegistration(HttpServletRequest request, JsonObject responseJson)
            throws SQLException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String pkG1 = request.getParameter("pk_g1");
        String pkG2 = request.getParameter("pk_g2");
        String pkH = request.getParameter("pk_h");

        if (username == null || password == null || pkG1 == null || pkG2 == null || pkH == null) {
            responseJson.addProperty("status", 400);
            responseJson.addProperty("message", "Missing required fields");
            return;
        }

        User user = new User(username, password, pkG1, pkG2, pkH);
        if (userDAO.register(user)) {
            responseJson.addProperty("status", 200);
            responseJson.addProperty("message", "success");
        } else {
            responseJson.addProperty("status", 409);
            responseJson.addProperty("message", "Username exists");
        }
    }

    // 普通用户登录
    private void handleUserLogin(HttpServletRequest request, JsonObject responseJson)
            throws SQLException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = userDAO.findByUsername(username);
        if (user == null) {
            responseJson.addProperty("status", 401);
            responseJson.addProperty("message", "User not found");
            return;
        }

        if (userDAO.validatePassword(password, user.getPassword())) {
            responseJson.addProperty("status", 200);
            responseJson.addProperty("message", "success");
        } else {
            responseJson.addProperty("status", 401);
            responseJson.addProperty("message", "Invalid credentials");
        }
    }

    // 管理员登录
    private void handleAdminLogin(HttpServletRequest request, JsonObject responseJson)
            throws SQLException {

        String username = request.getParameter("manager_name");
        String password = request.getParameter("manager_pass");

        User user = userDAO.findByUsername(username);
        if (user == null || !"admin".equals(user.getRole())) {
            responseJson.addProperty("status", 403);
            responseJson.addProperty("message", "Access denied");
            return;
        }

        if (userDAO.validatePassword(password, user.getPassword())) {
            responseJson.addProperty("status", 200);
            responseJson.addProperty("message", "success");
        } else {
            responseJson.addProperty("status", 401);
            responseJson.addProperty("message", "Invalid credentials");
        }
    }

    // 普通用户登录
    private void handleGetAllUsers(HttpServletRequest request, JsonObject responseJson) throws SQLException {
        List<User> users = userDAO.getAllUsers();
        if (users != null) {
            // 创建 JsonArray 来存储用户列表
            JsonArray jsonUsersArray = new JsonArray();

            // 遍历用户列表，将每个 User 对象添加到 JsonArray
            for (User user : users) {
                JsonObject userJson = new JsonObject();
                userJson.addProperty("username", user.getUsername());
                userJson.addProperty("password", user.getPassword());
                // 添加其他字段...
                jsonUsersArray.add(userJson);
            }

            responseJson.addProperty("status", 200);

            // 将 jsonResponse 添加到 responseJson 中
            responseJson.add("data", jsonUsersArray);
            return;
        }

        // 如果 users 为 null，可以返回错误信息
        responseJson.addProperty("status", 404);
        responseJson.addProperty("message", "No users found");
    }

    // 获取用户公钥
    private void handleGetPublicKey(HttpServletRequest request, JsonObject responseJson)
            throws SQLException {

        String username = request.getParameter("username");
        User user = userDAO.findByUsername(username);

        if (user != null) {
            JsonObject publicKeys = new JsonObject();
            publicKeys.addProperty("pkG1", user.getPkG1());
            publicKeys.addProperty("pkG2", user.getPkG2());
            publicKeys.addProperty("pkH", user.getPkH());
            responseJson.add("data", publicKeys);
            responseJson.addProperty("status", 200);
        } else {
            responseJson.addProperty("status", 404);
            responseJson.addProperty("message", "User not found");
        }
    }

    private void sendError(HttpServletResponse response, int code, String message)
            throws IOException {

        response.setStatus(code);
        JsonObject error = new JsonObject();
        error.addProperty("status", code);
        error.addProperty("message", message);
        response.getWriter().print(error.toString());
    }
}